import { meassageMap } from "@userList/utils";
import { fetchList, tmp_proxy, refreshTable } from ".";
import { operateType, merchantList, drawerFormState } from "./store";
import { labelStatusMap } from "./dict";
export const drawerLoading = ref(false);
export const drawerVisible = ref(false);
export const drawerTitle = ref("");
export const drawer_disable_ok_button = computed(() => {
  return (
    isEmptyType(drawerFormState.status) ||
    isEmptyType(drawerFormState.name) ||
    isEmptyType(drawerFormState.username)
  );
});
const defineApiMap = (string, formState) => {
  const { servername, ...data } = formState;
  const addChannel = async () => await channelApi.list.add(data);
  const updateChannel = async () =>
    await channelApi.list.update({
      ...data,
      merchant_uid: data.merchant_uid || 0,
    });
  const apiMap = new Map([
    ["add", addChannel],
    ["update", updateChannel],
  ]);
  return new Map([[/^[a-zA-Z_]*$/, apiMap.get(string)]]);
};

const handleSubmitApiTask = async () => {
  const formState = drawerFormState;
  const loading = drawerLoading;
  const visible = drawerVisible;
  const string = operateType.value;
  try {
    let [, api]: any = [...defineApiMap(string, formState)].find(([key]) =>
      key.test(string)
    );
    loading.value = true;
    const result: any = await api();
    if (result.code != 200) return message.error(result.message);
    visible.value = false;
    const [, showMessage] = [...meassageMap(refreshTable, fetchList)].find(
      ([key]) => key.test(string)
    );
    showMessage();
  } catch (e: any) {
    message.error(e.message);
  } finally {
    loading.value = false;
  }
};
export const drawerConfig = () => {
  const copyText = (text: string) => {
    const input = createElNode("input");
    input.setAttribute("readonly", "readonly");
    input.setAttribute("value", text);
    document.body.appendChild(input);
    // @ts-ignore
    input.select();
    // @ts-ignore
    input.setSelectionRange(0, 9999);
    if (document.execCommand("copy")) {
      document.execCommand("copy");
      message.success($t("base.copySucess"));
    }
    document.body.removeChild(input);
  };
  const rules = {
    username: [
      {
        required: true,
        trigger: ["blur", "change"],
        validator: (rule: any, value: string) => {
          if (!value) {
            return Promise.reject($t("placeholder19"));
          }
          if (
            !(
              /^[0-9a-zA-Z_]{1,}$/.test(value) &&
              value?.length >= 4 &&
              value?.length <= 6
            )
          ) {
            return Promise.reject(
              $t("placeholder108") + "4-6" + $t("base.digit")
            );
          }
          return Promise.resolve();
        },
      },
    ],
    name: {
      required: true,
      trigger: ["blur", "change"],
      validator: (rule: any, value: string) => {
        if (!value) {
          return Promise.reject($t("placeholder20"));
        }
        if (
          !(
            /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value) &&
            value?.length >= 2 &&
            value?.length <= 12
          )
        ) {
          return Promise.reject(
            $t("placeholder109") + "2-12" + $t("base.digit")
          );
        }
        return Promise.resolve();
      },
    },
    merchant_uid: {
      required: true,
      trigger: ["blur", "change"],
      message: getProxyT("placeholder24"),
    },
  };

  const handleSubmit = (type: string) => handleSubmitApiTask();
  const defineDrawer = {
    width: "800px",
    drawerInstance: ref(null),
    disable_ok_button: drawer_disable_ok_button,
    loading: drawerLoading,
    visible: drawerVisible,
    title: drawerTitle,
    maskClosable: true,
    formState: drawerFormState,
    get dominPrefix() {
      const prefix = /^https/.test(defineDrawer.formState.servername)
        ? "https://"
        : "http://";
      return prefix;
    },
    get dominSuffix() {
      const prefix = /^https/.test(defineDrawer.formState.servername)
        ? "https://"
        : "http://";
      return (
        defineDrawer.formState.servername?.replace(prefix, "") +
        (operateType.value === "add"
          ? defineDrawer.formState.username ?? ""
          : "")
      );
    },
    okIcon: "",
    cancelIcon: "",
    drawerList: [],
    slot: {
      extra_form_item: () => {
        const { formState, dominSuffix, dominPrefix } = defineDrawer;
        return (
          <>
            <s-title>{$t("base.baseInfo")}</s-title>
            <a-row class="s-drawer-extra-row" gutter={16}>
              <a-col span={12}>
                <a-form-item
                  label={$t("table65")}
                  name="username"
                  extra={$t("placeholder27")}
                  required={true}
                >
                  {withDirectiveInput({
                    vNode: (
                      <a-input
                        maxlength="6"
                        placeholder={$t("placeholder19")}
                        disabled={operateType.value === "update"}
                        vModel:value={formState.username}
                      />
                    ),
                  })}
                </a-form-item>
              </a-col>
              <a-col span={12}>
                <a-form-item label={$t("table66")} name="name" required={true}>
                  {withDirectiveInput({
                    vNode: (
                      <a-input
                        placeholder={$t("placeholder20")}
                        maxlength="12"
                        vModel:value={formState.name}
                      />
                    ),
                  })}
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="s-drawer-extra-row">
              <s-title>{$t("base.extendAddress")}</s-title>
            </a-row>
            <a-row class="s-drawer-extra-row" gutter={16}>
              <a-col span={12}>
                <a-form-item
                  label={$t("table67")}
                  name="servername"
                  extra={$t("placeholder22")}
                >
                  <a-row>
                    <a-col span="18">
                      {withDirectiveInput({
                        vNode: (
                          <a-input
                            value={dominSuffix}
                            placeholder={$t("placeholder21")}
                            disabled="true"
                            addon-before={dominPrefix}
                          />
                        ),
                      })}
                    </a-col>
                    <a-col>
                      <s-button
                        disabled={!formState.username}
                        type="link"
                        onClick={() =>
                          copyText(
                            formState.servername +
                              (operateType.value === "update"
                                ? ""
                                : formState.username)
                          )
                        }
                      >
                        {$t("base.copy")}
                      </s-button>
                    </a-col>
                  </a-row>
                </a-form-item>
              </a-col>

              <a-col span={12}>
                <a-form-item label={$t("table78")} name="remark">
                  {withDirectiveInput({
                    bindingValue: "textFilter",
                    vNode: (
                      <a-textarea
                        vModel:value={formState.remark}
                        rows="4"
                        show-count
                        maxlength="100"
                        placeholder={$t("placeholder23")}
                      />
                    ),
                  })}
                </a-form-item>
              </a-col>
            </a-row>

            <s-title>{$t("base.seniorSet")}</s-title>
            <a-row class="s-drawer-extra-row" gutter={16}>
              <a-col span={12}>
                <a-form-item
                  label={$t("table14")}
                  name="merchant_uid"
                  extra={$t("placeholder28")}
                >
                  {withDirectiveInput({
                    bindingValue: "textFilter",
                    vNode: (
                      <a-select
                        vModel:value={formState.merchant_uid}
                        allowClear={true}
                        show-search={true}
                        options={merchantList.value}
                        filter-option={(input: string, option: any) => {
                          return (
                            option.label
                              ?.toLowerCase()
                              ?.indexOf(input.toLowerCase()) >= 0
                          );
                        }}
                        placeholder={$t("placeholder24")}
                      />
                    ),
                  })}
                </a-form-item>
              </a-col>

              <a-col span={12}>
                <a-form-item
                  label={$t("table31")}
                  required="true"
                  name="status"
                >
                  <a-radio-group vModel:value={formState.status}>
                    {labelStatusMap
                      .filter(({ label, value }: any) => {
                        return +value != Infinity;
                      })
                      .map((item: any) => (
                        <>
                          <a-radio value={item.value}>
                            {item.label?.value}
                          </a-radio>
                        </>
                      ))}
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
          </>
        );
      },
      extra: () => (
        <>
          <a-space size={8}>
            <s-button
              icon={renderIcon("icon-cancel")}
              onClick={() =>
                tmp_proxy.$confirm({
                  closable: true,
                  maskClosable: true,
                  icon: null,
                  title: () => <>{$t("base.prompt")}</>,
                  style: {
                    top: "30%",
                  },
                  content: <>{$t("base.cancelTips")}</>,
                  onOk: () => (drawerVisible.value = false),
                })
              }
            >
              {$t("base.cancel")}
            </s-button>
            <s-button
              icon={renderIcon("icon-tubiao_tijiao")}
              disabled={drawer_disable_ok_button.value}
              loading={drawerLoading.value}
              type="primary"
              onClick={handleSubmit}
            >
              {$t("base.save")}
            </s-button>
          </a-space>
        </>
      ),
    },
  };
  return defineDrawer;
};
